package com.zahb.qadx.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.TrainDetailsBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.activity.OfflineTrainDetailActivity;
import com.zahb.qadx.ui.adapter.OfflineTrainAdapter;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.Tips;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class OfflineTrainFragment extends BaseFragmentExt implements OnRefreshLoadMoreListener {

    private LinearLayoutCompat llEmpty;

    private OfflineTrainAdapter offlineTrainAdapter = new OfflineTrainAdapter(R.layout.item_offline_train);

    private RecyclerView recyc;
    private SmartRefreshLayout refreshLayout;
    private int classid = 0;
    private static final int pagesize = 10;
    private int pagenum = 1;
    private int totalPage = 1;

    public TrainDetailsBean trainDetailsBean;

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    @Override
    protected int getLayout() {
        return R.layout.fragment_offline_train;
    }

    @Override
    protected void initViews(View rootView) {

        classid = getArguments().getInt("id", 0);

        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        recyc = rootView.findViewById(R.id.recyc);
        llEmpty = rootView.findViewById(R.id.ll_empty);

        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setOnRefreshLoadMoreListener(this);

        recyc.setAdapter(offlineTrainAdapter);
        recyc.setLayoutManager(new LinearLayoutManager(getActivity()));

        offlineTrainAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(getActivity(), OfflineTrainDetailActivity.class);
            intent.putExtra("data", offlineTrainAdapter.getItem(position));
            startActivity(intent);
        });

        //getData();
    }

    private boolean mFirstLoad = true;

    @Override
    public void onResume() {
        super.onResume();
        if (mFirstLoad) {
            mFirstLoad = false;
            showSkeleton();
        }
        onRefresh(refreshLayout);
    }

    //培训列表两个列表数据源
    public void getData() {
        addDisposable(RetrofitService.getNetService()
                .stuOfflineClassPlanPage(classid, pagenum, pagesize)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        totalPage = response.getData().getPages();
                        if (pagenum == 1) {
                            offlineTrainAdapter.setList(response.getData().getRecords());
                        } else {
                            offlineTrainAdapter.addData(response.getData().getRecords());
                        }
                        isVisible(offlineTrainAdapter.getItemCount() > 0);
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    Tips.RequestError(getActivity());
                    hideSkeleton();
                }));
    }

    private void isVisible(boolean flag) {
        if (recyc.getAdapter() instanceof OfflineTrainAdapter) {
            if (flag) {
                recyc.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
            } else {
                llEmpty.setVisibility(View.VISIBLE);
                recyc.setVisibility(View.GONE);
            }
        }
    }

    private final int topMargin = DisplayUtil.dip2px(16f);

    private RecyclerView.ItemDecoration mItemDecoration = new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            if (parent.getAdapter() == null) return;
            outRect.setEmpty();
            outRect.top = topMargin;
        }
    };

    private void showSkeleton() {
        refreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(recyc)
                .adapter(offlineTrainAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_task_skeleton)
                .show();
        ViewCompat.setPaddingRelative(recyc, topMargin, 0, topMargin, 0);
        recyc.addItemDecoration(mItemDecoration);
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                refreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
                ViewCompat.setPaddingRelative(recyc, 0, 0, 0, 0);
                recyc.removeItemDecoration(mItemDecoration);
                isVisible(offlineTrainAdapter.getItemCount() > 0);
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (pagenum + 1 > totalPage) {
            refreshLayout.finishLoadMore();
        } else {
            pagenum++;
            getData();
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pagenum = 1;
        getData();
    }
}
